package com.pactera.integral.util;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pactera.integral.dao.SummaryScoreDao;
import com.pactera.integral.dao.UserAdditionalScoreDao;
import com.pactera.integral.dao.UserDao;
import com.pactera.integral.dao.UserPerformanceScoreDao;
import com.pactera.integral.entity.SummaryScore;

/*import com.pactera.core.dao.UserDao;
import com.pactera.integral.dao.SummaryScoreDao;
import com.pactera.integral.dao.UserAdditionalScoreDao;
import com.pactera.integral.dao.UserPerformanceScoreDao;
import com.pactera.integral.entity.SummaryScore;*/

/**
 * 每次审核分数后计算分数到summaryScore中
 * 
 * @author JJ
 *
 */
@Component
public class SumScore {
	@Autowired
	private UserAdditionalScoreDao userAdditionalScoreDao;

	@Autowired
	private UserPerformanceScoreDao userPerformanceScoreDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private SummaryScoreDao summaryScoreDao;

	private static SumScore sumScore;

	@PostConstruct
	public void init() {
		sumScore = this;
		sumScore.summaryScoreDao = this.summaryScoreDao;
		sumScore.userAdditionalScoreDao = this.userAdditionalScoreDao;
		sumScore.userPerformanceScoreDao = this.userPerformanceScoreDao;
		sumScore.userDao = this.userDao;
	}

	public static void sum(String staffId, Integer year, Integer month) {
		String userId;
		int additionalScore;
		int performanceScore;
		SummaryScore existingScore = sumScore.summaryScoreDao.findByStaffIdAndYearAndMonth(staffId, year, month);
		userId = sumScore.userDao.findByStaffId(staffId).getUserId();
		additionalScore = checkScore(sumScore.userAdditionalScoreDao.findByDetail(userId, year, month));
		performanceScore = checkScore(sumScore.userPerformanceScoreDao.findByDetail(userId, year, month));
		if (null != existingScore) {
			existingScore.setAdditionalScore(additionalScore);
			existingScore.setPerformanceScore(performanceScore);
			sumScore.summaryScoreDao.save(existingScore);
		} else {
			SummaryScore summaryScore = new SummaryScore();
			summaryScore.setAdditionalScore(additionalScore);
			summaryScore.setPerformanceScore(performanceScore);
			summaryScore.setUserId(userId);
			summaryScore.setStaffId(staffId);
			summaryScore.setYear(year);
			summaryScore.setMonth(month);

			// TODO 分数类型(ScoreType)预设为组员“TM”
			summaryScore.setScoreType("TM");
			sumScore.summaryScoreDao.save(summaryScore);
		}
	}

	private static Integer checkScore(Integer score) {
		if (null != score) {
			return score;
		} else {
			return 0;
		}
	}

}
